# -*- coding: utf-8 -*-
from __future__ import print_function, division
#系统库
import json
#第三方库
import tornado.web
import tornado.template
#自定义库
import local
import Serverlib
import hall

logger = Serverlib.logging.getLogger('SERVER')

message_queue = {}


#主体
class Handler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self, *args, **kwargs):
        u_id = self.get_secure_cookie("agot_user_id")
        if u_id == None:
            ret = {
                "code": 255,
                "errormsg": local.String.HL_ER_usernotexist
            }
            self.finish(json.dumps([ret]))
            return
        self.user_id = long(u_id)
        if self.user_id in message_queue:
            msg = [item for item in message_queue[self.user_id]]
            string = json.dumps(msg)
            self.finish(string)
            del(message_queue[self.user_id])
        player = hall.gamehall.get_logon_player(self.user_id)
        if player != None:
            if player.comet == None:
                logger.debug("[{0}] comet ready".format(self.user_id))
            player.comet = self
            self.player = player

    def sent(self, dictdata):
        # Closed client connection
        if self.user_id not in message_queue:
            message_queue[self.user_id] = []
        message_queue[self.user_id].append(dictdata)
        if self.request.connection.stream.closed():
            return False
        string = json.dumps(message_queue[self.user_id])
        self.finish(string)
        del(message_queue[self.user_id])
        return True

    def on_connection_close(self):
        hall.gamehall.lost_connection(self.user_id)
        self.player = None
